import { basic } from '../mixins/basic'

Component({
  behaviors: [basic],

  options: {
    multipleSlots: true 
  },
  /**
   * 组件的属性列表
   */
  properties: {
    delay: { // 动画延迟时间 (s)
      type: Number,
      value: 1
    },
    speed: { // 滚动速率 (px/s)
      type: Number,
      value: 50
    },
    scrollable: { // 是否在长度溢出时滚动播放
      type: Boolean,
      value: true
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    wrapWidth: 0,
    contentWidth: 0,
    duration: 0,
    animation: null,
    resetAnimation: null
  },

  created() {
    this.setData({
      resetAnimation: wx.createAnimation({
        duration: 0,
        timingFunction: 'linear'
      })
    })
  },
  
  ready() {
    this.init()
  },

  detached() {
    this.timer && clearTimeout(this.timer);
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      Promise.all([
        this.getRect('.marquee-swiper'),
        this.getRect('.marquee-content')
      ]).then((rects) => {
        console.log('init rects', rects)
        const [swiperRect, contentRect] = rects
        console.log('swiperRect', swiperRect)
        console.log('contentRect', contentRect)
        if (contentRect == null ||
          swiperRect == null ||
          !contentRect.width ||
          !swiperRect.width) {
          return
        }
        const { speed, scrollable, delay } = this.data
        if (scrollable && swiperRect.width < contentRect.width) {
          const duration = (contentRect.width / speed) * 1000;
          this.setData({
            wrapWidth: swiperRect.width,
            contentWidth: contentRect.width,
            duration: duration,
            animation: wx.createAnimation({
              duration,
              timingFunction: 'linear',
              delay
            })
          })
          // this.wrapWidth = swiperRect.width;
          // this.contentWidth = contentRect.width;
          // this.duration = duration;
          // this.animation = wx.createAnimation({
          //     duration,
          //     timingFunction: 'linear',
          //     delay
          // });
          this.scroll();
        }
      })
    },
    scroll () {
      this.timer && clearTimeout(this.timer);
      this.timer = null;
      this.setData({
        animationData: this.resetAnimation
          .translateX(this.wrapWidth)
          .step()
          .export()
      });
    }
  }
})
